/*
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-07-11 20:01:53
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-16 16:41:13
 * @FilePath: /XMate-h5/src/store/modules/minutes/utils/speechOverview.ts
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
 */
import {
  AsrObject,
  SpeechOverview,
  CustomerRoles,
  InternalPartner,
  SpeechOverviewType
} from "@/types/minutes/store.type";

/**
 * 根据字幕列表生成发言人统计数据
 * @param asrList 字幕列表
 * @param customerRoles 客户角色数据
 * @param internalPartners
 * @returns 发言人统计数组
 */
export function generateSpeechOverview(
  asrList: AsrObject[],
  customerRoles: CustomerRoles[] = [],
  internalPartners: InternalPartner[] = []
): SpeechOverview[] {





  // 计算总字幕时长
  const totalAsrDuration = asrList.reduce(
    (sum, item) => sum + item.duration,
    0
  );

  let speechArr: SpeechOverview[] = asrList.reduce(
    (acc: SpeechOverview[], asrItem: AsrObject) => {
      let currentSpeech: SpeechOverview | undefined = acc.find(
        v => v.uid === asrItem.ui
      );
      if (!currentSpeech) {
        let formData = null;
        let type = SpeechOverviewType.UNKNOWN;
        formData =
          customerRoles.find(v => v.ui === asrItem.ui)?.formData || null;


          console.log("customerRoles: ", customerRoles);
          console.log("internalPartners: ", internalPartners);
          console.log("asrItem: ", asrItem.ui);

        let findInternal = internalPartners.find(v => v.ui === asrItem.ui);

        if (findInternal) {
          type = SpeechOverviewType.INTERNAL_PARTNER;
          formData =
            internalPartners.find(v => v.ui === asrItem.ui)?.formData || null;
        } else {
          type = SpeechOverviewType.CUSTOMER_ROLE;
        }
        acc.push({
          name: asrItem.name,
          asrList: [asrItem],
          uid: asrItem.ui,
          percent: 0,
          formData: formData || null,
          total: asrItem.duration,
          position: internalPartners.find(v => v.ui === asrItem.ui)?.position || "",
          type
        });
      } else {
        currentSpeech.asrList.push(asrItem);
        currentSpeech.total += asrItem.duration;
      }
      return acc;
    },
    []
  );

  return speechArr
    .map(speaker => ({
      ...speaker,
      percent:
        totalAsrDuration > 0 ? (speaker.total / totalAsrDuration) * 100 : 0
    }))
    .sort((a, b) => b.percent - a.percent);
}
